<?php

namespace App\Http\Controllers\Setting;

use App\Exceptions\Fail;
use App\Http\Controllers\Controller;
use App\Http\Requests\Setting\UserIndexRequest;
use App\Http\Requests\Setting\UserStoreRequest;
use App\Models\User;
use App\Models\UserRelRole;
use Illuminate\Support\Str;

class UserController extends Controller
{
    public function index(UserIndexRequest $request): array
    {
        $params = $request->validated();
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 10;

        $model = User::query()->where('id', '>', 1)
            ->when($params['name'] ?? false, fn($query, $name) => $query->where('nickname', 'like', "%$name%"));
        $total = (clone $model)->count();
        $list = $model->with('roles')->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->orderBy('id', 'desc')
            ->get(['id', 'nickname', 'account', 'created_at', 'updated_at'])
            ->toArray();
        return $this->success(compact('list', 'total'));
    }

    public function store(UserStoreRequest $request): array
    {
        $params = $request->validated();
        if (User::query()->where('account', $params['account'])->first()) {
            throw new Fail('账号重复！！');
        }
        $roles = $params['roles'] ?? [];
        unset($params['roles']);
        $password = 'yg@' . Str::random('6');
        $params['password'] = password_hash($password, PASSWORD_DEFAULT);
        $id = User::query()->insertGetId($params);
        UserRelRole::query()->insert(array_map(fn($v) => ['role_id' => $v, 'user_id' => $id], $roles));
        return $this->success(compact('password'));
    }

    public function detail(int $id): array
    {
        $data = User::query()->find($id, ['id', 'nickname', 'account'])->toArray();
        $data['roles'] = UserRelRole::query()->where('user_id', $id)->first()->role_id;
        return $this->success($data);
    }

    public function update(int $id, UserStoreRequest $request): array
    {
        $params = $request->validated();
        $user = User::query()->findOrFail($id);
        if ($user->account !== $params['account'] && User::query()->where('account', $params['account'])->first()) {
            throw new Fail('账号重复！！');
        }

        $roles = $params['roles'] ?? [];
        unset($params['roles']);
        User::query()->where('id', $id)->update($params);
        UserRelRole::query()->where('user_id', $id)->delete();
        UserRelRole::query()->insert(array_map(fn($v) => ['user_id' => $id, 'role_id' => $v], $roles));
        return $this->success();
    }

    public function resetPwd(int $id): array
    {
        $password = 'yg@' . Str::random('6');
        User::query()->where('id', $id)->update([
            'password' => password_hash($password, PASSWORD_DEFAULT),
        ]);
        return $this->success(compact('password'));
    }
}
